// pages/detail/detail.js
var app = getApp();
import { service, wxapi } from '../../api';
var wxCharts = require('../../utils/wxcharts.js');
var pieChart = null;
var columnChart = null;
var columnChart1 = null;


const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight
const custprent = width/750


var chartData1 = {
  main: {
    title: '总成交量',
    data: [15, 20, 45, 37],
    categories: ['2012', '2013', '2014', '2015']
  }
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataInfo:{},//元数据
    photos:[],//轮播图
    staticmap:'',//小地图图标
    shops:[],//列表
    basic:{},
    mapinfo:{},//地图信息
    business:{},
    defaultData:[],
    others:[],
    statistics:{},
    hasLocation:false,
    location:{},
    // title: netData[index].shelfName, imgSrc:imgMap[type].imgSrc, cls: imgMap[type].name
    //tabs:[],  //选择栏目
    tabIndex:0,
    propertyfeemoney: '',
    propertyfeemoney: '',
    chartData:{},//第一个柱状图

    isshow:'' ,
    isshowask:'',
    columnSrc:'',
    social:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // if(getCurrentPages().length == 3)
    // {
    //   debugger
    //   getCurrentPages().splice(2,1)
    // }
    // console.log(getCurrentPages())
    var id = options.id; //id = 1734;
    
    var that=this;
    service.getDetail(id,( (res) => {
      var result = res.data.data;//总数据
      var basic = result.basic;
      var defaultData=[];

      for (var i in result.business.shops){
        // if(i==4){
        //   break;
        // }
        defaultData.push(result.business.shops[i]);
      }
      that.setData({
        dataInfo: result,
        basic: basic,
        imgUrls: basic.photos,
        staticmap: basic.staticmap,
        // shops: result.shops,
        mapinfo: result.mapinfo,
        business: result.business,
        defaultData:defaultData,
        photos: result.photos,
        others: result.others,
        propertyfeemoney: basic.propertyfee.split("元")[0]||0,
        propertyfeeunit: basic.propertyfee.split("元")[1],
        //tabs: tabs,
        statistics: result.statistics,
        social: result.social,
        location: {
          longitude: result.mapinfo.longitude,
          latitude: result.mapinfo.latitude
        }
      });
      this.pie();
      this.column();
      this.column1();
      
      wx.setNavigationBarTitle({
        title: this.data.basic.name//页面标题为路由参数
      })
    }))

    //this.getLocation();


    
  },
  select(e) {
    
    var id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: '/pages/detail/detail?id='+id
    })
  },
  // showMore:function(){
  //   var that=this;
  //   that.setData({
  //     defaultData: that.data.business.shops
  //   })
  // },
  bind_tal:function(){
    wx.makePhoneCall({
      phoneNumber: '0512-80859090' //仅为示例，并非真实的电话号码  
    })  
  },
  tabChange:function(e){
    var showtype = e.currentTarget.dataset.type;
    var name = e.currentTarget.dataset.name;
    var data=[];
    var business = this.data.business;
    if (showtype > 0){
      for (var i in business.shops) {
        if (business.shops[i].format == name) {
          data.push(business.shops[i]);
        }
      }
    }else{
      data = business.shops;//.slice(0, 4);
    }
    
    this.setData({
      tabIndex: showtype,
      defaultData:data
    });
  },
  formSubmit:function(e){
    if (e.detail.value.input==""){
      return false;
    }
    var param={
      "name":"张三",
      "phone": e.detail.value.input
    };
    service.makeanappointment(param, ((res) => {
      if (res.data!=null){
        wx.showToast({
          title: res.data.message,
          icon: 'success',
          duration: 2000
        })

        this.setData({
          isshow: ''
        })
      }
    }))
  },
  askcontent: function () {
    this.setData({
      isshowask: 'display:block'
    })
  },
  bind_cancel: function () {
    this.setData({
      isshowask: ''
    })
  },
  yuyue:function(){
    // var param={};
    // service.makeanappointment(id, ((res) => {

    // }))
    this.setData({
      isshow:'display:block'
    })
  },
  yuyuehide: function (e) {
    // var param={};
    // service.makeanappointment(id, ((res) => {

    // }))
    this.setData({
      isshow: 'display:none'
    })
  },
  touchHandler: function (e) {
    console.log(pieChart.getCurrentDataIndex(e));
  },
  pie:function(){
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    var formats = this.data.statistics.formats
    var series=[];
    for(var i in formats){
      series.push(
        {
          "name":formats[i].name,
          "data": formats[i].count
        }
      )
    }

    //debugger
    pieChart = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas',
      type: 'pie',
      series: series,
      width: windowWidth,
      height: 300,
      dataLabel: true,
    });
    console.log(custprent);
      let that = this;
      setTimeout(()=>{
          wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: width,
              height: height,
              destWidth: width * 2,
              destHeight: height  * 2,
              quality: 1,
              canvasId: 'pieCanvas',
              success: function (res) {
                  console.log(res)
                  that.setData({
                      peiSrc : res.tempFilePath
                  })
              }
          })

      },2000)


  
  },
  column:function(){
    var consumption = this.data.statistics.consumption;
    var chartData={};
    chartData.title="房屋均价";
    var data=[];
    data.push(consumption.percapitaconsumption.city); 
    data.push(consumption.percapitaconsumption.area);
    data.push(consumption.percapitaconsumption.surround);
    chartData.data = data
    var categories=[];
    categories.push("苏州");
    categories.push("区域");
    categories.push("铺源周围");
    // categories.push(consumption.meanprice.city);
    // categories.push(consumption.meanprice.area);
    // categories.push(consumption.meanprice.surround);
    chartData.categories = categories;

    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    console.log(chartData.categories);
    columnChart = new wxCharts({
      canvasId: 'columnCanvas',
      type: 'column',
      // animation: true,
      categories: chartData.categories,
      // categories: ['2012', '2013', '2014'],
      // dataLabel:true,
      series: [{
        name: '房屋均价',
        data: chartData.data,
        // format: function (val, name) {
        //   return val.toFixed(2) + '万';
        // }
      }],
      yAxis: {
        // format: function (val) {
        //   return val + '万';
        // },
        // title: 'hello',
        min: 0
      },
      xAxis: {
        disableGrid: false,
        type: 'calibration'
      },
      extra: {
        column: {
          width: 15
        }
      },
      width: windowWidth,
      height: 200,
    });
    let that = this;
    setTimeout(() => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: width,
        height: 480 * custprent,
        destWidth: width * 2,
        destHeight: 480 * custprent * 2,
        quality: 1,
        canvasId: 'columnCanvas',
        success: function (res) {
          console.log(res.tempFilePath)
          that.setData({
            columnSrc: res.tempFilePath
          })
        }
      })

    }, 4000)
  },
  column1: function () {
    var consumption = this.data.statistics.consumption;
    var chartData1 = {};
    chartData1.title = "人均消费";
    var data = [];
    data.push(consumption.meanprice.city);
    data.push(consumption.meanprice.area);
    data.push(consumption.meanprice.surround);
    chartData1.data = data
    var categories = [];
    categories.push("苏州");
    categories.push("区域");
    categories.push("铺源周围");
    chartData1.categories = categories;
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }

    columnChart1 = new wxCharts({
      canvasId: 'columnCanvas1',
      type: 'column',
      animation: true,
      categories: chartData1.categories,
      series: [{
        name: '人均消费',
        data: chartData1.data,
        // format: function (val, name) {
        //   return val.toFixed(2) + '万';
        // }
      }],
      yAxis: {
        // format: function (val) {
        //   return val + '万';
        // },
        // title: 'hello',
        min: 0
      },
      xAxis: {
        disableGrid: false,
        type: 'calibration'
      },
      extra: {
        column: {
          width: 15
        }
      },
      width: windowWidth,
      height: 200,
    });
    let that = this;
    setTimeout(() => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: width,
        height: height,
        destWidth: width * 2,
        destHeight: height * 2,
        quality: 1,
        canvasId: 'columnCanvas1',
        success: function (res) {

          console.log(res)
          that.setData({
            columnSrc1: res.tempFilePath
          })
        },
        fail: function (e) {

        },
        complete: function (e) {

        }
      })

    }, 6000)
  },
  call:function(){
    wx.makePhoneCall({
      phoneNumber: '0512-80859090' //仅为示例，并非真实的电话号码
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  //获取经纬度
  getLocation: function (e) {
    console.log(e)
    var that = this;
    wx.getLocation({
      success: function (res) {
        // success
        console.log(res)
        that.setData({
          hasLocation: true,
          location: {
            longitude: res.longitude,
            latitude: res.latitude
          }
        })
      }
    })
  },
  //根据经纬度在地图上显示
  openLocation: function (e) {
    //console.log("openLocation" + e)
    //var value = e.detail.value
    wx.openLocation({
      longitude: Number(this.data.location.longitude),
      latitude: Number(this.data.location.latitude)
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    debugger
    　　var that = this;
    　　// 设置菜单中的转发按钮触发转发事件时的转发内容
    　　var shareObj = {
        title: that.data.social.title,        // 默认是小程序的名称(可以写slogan等)
        path: '/pages/detail/detail?id=' + that.data.basic.id,        // 默认是当前页面，必须是以‘/’开头的完整路径
      　　　　imgUrl: '',     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      　　　　success: function (res) {
        　　　　　　// 转发成功之后的回调
        　　　　　　if (res.errMsg == 'shareAppMessage:ok') {
        　　　　　　}
      　　　　},
            fail: function (res) {
        　　　　　　// 转发失败之后的回调
        　　　　　　if (res.errMsg == 'shareAppMessage:fail cancel') {
          　　　　　　　　// 用户取消转发
        　　　　　　} else if (res.errMsg == 'shareAppMessage:fail') {
          　　　　　　　　// 转发失败，其中 detail message 为详细失败信息
        　　　　　　}}
      // 　　　　},
      // 　　　　complete: fucntion(){
      //   　　　　　　// 转发结束之后的回调（转发成不成功都会执行）
      // 　　　　}
  　　};
  　　// 来自页面内的按钮的转发
  　　if(options.from == 'button') {
    　　　　var eData = options.target.dataset;
    
    　　　　console.log(eData.id);     // shareBtn
    　　　　// 此处可以修改 shareObj 中的内容
        shareObj.path = '/pages/detail/detail?id=' + eData.id;
  　　}
　　// 返回shareObj
　　return shareObj;
}
})